package com.example.administrator.baikangxing.fragment;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.administrator.baikangxing.Dao.GetContact;
import com.example.administrator.baikangxing.Dao.OperateData;
import com.example.administrator.baikangxing.MyApplication;
import com.example.administrator.baikangxing.R;
import com.example.administrator.baikangxing.activity.MessageActivity;
import com.example.administrator.baikangxing.activity.VoiceActivity;
import com.example.administrator.baikangxing.adapter.CallAdapter;
import com.example.administrator.baikangxing.adapter.CallContactAdapter;
import com.example.administrator.baikangxing.bean.BindDevice;
import com.example.administrator.baikangxing.bean.ContactUser;
import com.example.administrator.baikangxing.config.Constants;
import com.example.administrator.baikangxing.config.Url;
import com.example.administrator.baikangxing.utils.CommomUtil;
import com.example.administrator.baikangxing.utils.HttpUtil;
import com.example.administrator.baikangxing.utils.LogUtil;
import com.example.administrator.baikangxing.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class CallFragment extends BaseFragment implements ActivityCompat.OnRequestPermissionsResultCallback{

    private ListView call_watch;
    private ListView call_contact;
    private final int REQUEST_CODE = 1000;
    private ArrayList<ContactUser> phoneNumberFromMobile;
    private ArrayList<BindDevice> bindDevices;

    @Override
    public int getContentViewLayoutId() {
        return R.layout.fragment_call;
    }

    @Override
    public void initView() {
        call_watch = findView(R.id.call_watch);
        call_contact = findView(R.id.call_contact);
    }

    @Override
    public void initListener() {
        call_contact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), MessageActivity.class);
                ContactUser contactUser = phoneNumberFromMobile.get(i);
                intent.putExtra(Constants.USER_INFO,contactUser);
                startActivity(intent);
            }
        });
        call_watch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), VoiceActivity.class);
                intent.putExtra(Constants.CHAT_DEVID,bindDevices.get(i));
                startActivity(intent);
            }
        });
    }

    @Override
    public void initData() {
        //检查权限
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.GET_ACCOUNTS)
                != PackageManager.PERMISSION_GRANTED) {
            //进入到这里代表没有权限.

            if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.GET_ACCOUNTS)){
                //已经禁止提示了
                Toast.makeText(MyApplication.context, "您已禁止该权限，需要重新开启。", Toast.LENGTH_SHORT).show();
            }else{
                CallFragment.this.requestPermissions(new String[]{Manifest.permission.GET_ACCOUNTS}, REQUEST_CODE);
            }

        } else {
            getPhoneBook();
        }
        //PermissionUtils.requestPermission(getActivity(), PermissionUtils.CODE_GET_ACCOUNTS, mPermissionGrant);
        getWatchList();//获取手表联系人
    }

    private void getWatchList() {
        String[] values = new String[]{OperateData.getStringData(getContext(),Constants.USER_NAME),"ext"};
        HttpUtil.getInstance().postString(Url.get_dev_list, new String[]{"user", "ext"}, values, new HttpUtil.CallBackPostString() {
            @Override
            public void onSuccess(JSONObject successString) {
                try {
                    if(successString.getString("errorCode").equals("0")){
                        JSONArray message = successString.getJSONArray("message");
                        bindDevices = CommomUtil.parserJsonArrayToList(message, BindDevice.class);
                        if(bindDevices.size()>0 ){//存在绑定设备
                            CallAdapter adapter = new CallAdapter(bindDevices);
                            call_watch.setAdapter(adapter);
                        }else {/*没有绑定设备，暂不处理*/
                            LogUtil.e("暂无绑定设备");
                        }
                    }else {//获取失败
                        ToastUtil.showToast(successString.getString("errorinfo"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(JSONObject failString) {

            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {

            }
        });
    }

    private void getPhoneBook() {
        phoneNumberFromMobile = GetContact.getPhoneNumberFromMobile(getContext());
        CallContactAdapter adapter = new CallContactAdapter(phoneNumberFromMobile);
        call_contact.setAdapter(adapter);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case REQUEST_CODE:
                if(grantResults.length >0 &&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                //用户同意授权
                LogUtil.e("走了这个方法");
                getPhoneBook();
            }else{
                //用户拒绝授权
            }
            break;
        }
    }
}
